<template>
  <div class="add-chart">
    <el-row :gutter="24">
      <el-col :span="12">
        <el-card :title="'智能分析'" class="hone">
          <el-form
            ref="form"
            :model="form"
            label-position="left"
            label-width="80px"
            :rules="rules"
            @submit.native.prevent="onSubmit"
          >
            <el-form-item label="分析目标" prop="goal">
              <el-input
                type="textarea"
                :placeholder="'请输入你的分析需求，比如：分析网站用户的增长情况'"
                v-model="form.goal"
              />
            </el-form-item>

            <el-form-item
              label="图表类型"
              prop="chartType"
              :rules="[
                {
                  required: true,
                  message: '请选择图表类型',
                  trigger: 'change',
                },
              ]"
            >
              <el-select v-model="form.chartType" placeholder="请选择">
                <el-option label="折线图" value="line"></el-option>
                <el-option label="柱状图" value="bar"></el-option>
                <el-option label="堆叠图" value="scatter"></el-option>
                <el-option label="饼图" value="pie"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="原始数据"
              prop="file"
              :rules="[
                { required: true, message: '请上传文件', trigger: 'change' },
              ]"
            >
              <el-upload
                class="upload-demo"
                :action="uploadAction"
                :multiple="false"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :on-exceed="handleExceed"
                :on-change="handleChange"
                :file-list="fileList"
                :limit="1"
                :auto-upload="false"
                accept=".xls, .xlsx, .csv"
              >
                <el-button slot="trigger" type="primary"
                  ><i class="el-icon-upload"></i> 上传 xlsx、xls 或 csv
                  文件</el-button
                >
                <div slot="tip" class="el-upload__tip">
                  文件大小不超过 {{ size }}，只能上传
                  {{ limit }} 个文件，且只支持 xls、xlsx、csv 格式。
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="submitting"
                :disabled="submitting"
                @click="onSubmit"
                >提交</el-button
              >
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card header="分析结论">
          <div v-if="chart.genResult">{{ chart.genResult }}</div>
          <div v-else>请先在左侧进行提交</div>
        </el-card>
        <el-card header="可视化图表">
          <div v-if="option">
            <div ref="chartContainer" style="height: 300px"></div>
          </div>
          <div v-else>请先在左侧进行提交</div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { generateResultByAiAnsynUsingPOST } from '@/api/employee'
import { startLoading, stopLoading } from './load'
import * as echarts from 'echarts'

@Component({
  components: {},
})
export default class extends Vue {
  private form = {
    goal: '',
    chartType: '',
    file: '',
  }

  private chart = {
    genResult: '',
  }

  private option: any = {}

  private uploadAction = 'http://lixp.online:8999/background/aiChart/genByAI'

  private rules = {
    goal: [{ required: true, message: '请输入分析目标', trigger: 'blur' }],
    chartType: [
      { required: true, message: '请选择图表类型', trigger: 'change' },
    ],
    file: [{ required: true, message: '请上传文件', trigger: 'change' }],
  }

  private fileList: any[] = []

  private size = '10MB'

  private limit = 1

  private submitting = false

  private async onSubmit() {
    const { chartType, file, goal } = this.form
    const loading = startLoading()
    try {
      const res = await generateResultByAiAnsynUsingPOST(
        file.raw,
        chartType,
        goal
      )
      console.log(chartType)
      if (res.data.code === 1) {
        this.chart.genResult = res.data.data.genResult
        const chartData = JSON.parse(res.data.data.genChart)
        console.log(chartData)
        const chartContainer: any = this.$refs.chartContainer
        console.log(chartContainer)
        const myChart = echarts.init(chartContainer)
        myChart.setOption(chartData)
        console.log(myChart)
        myChart.setOption({
          title: {
            text: null,
            textStyle: {
              fontSize: 16,
              lineHeight: 32,
            },
          },
        })
        this.$message.success('分析成功')
      } else {
        this.$message.error('分析失败')
      }
    } catch (error) {
      this.$message.error('提交数据失败' + error.message)
      console.log(error)
    } finally {
      stopLoading(loading)
    }
  }

  private resetForm() {
    ;(this.$refs.form as any).resetFields()
  }

  private beforeUpload(file: any) {
    const isSizeValid = file.size / 1024 / 1024 < 10
    const isTypeValid =
      file.type === 'application/vnd.ms-excel' ||
      file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'text/csv'
    if (!isSizeValid) {
      console.log(Error)
      return false
    }
    if (!isTypeValid) {
      this.$message.error('只能上传 xls、xlsx 或 csv 格式的文件')
      return false
    }

    this.form.file = file
    return isSizeValid && isTypeValid
  }

  private handleSuccess(response: any, file: any, fileList: any) {
    if (response.code !== 200) {
      this.$message.error(response.msg)
      return
    }
    this.fileList = fileList
    this.form.file = response.data.url
  }

  private handleExceed(files: any, fileList: any) {
    console.log('files', files)
    this.$message.warning('只能上传一个文件')
  }

  private handleChange(file: any, fileList: any) {
    this.form.file = file
  }

  private submitUpload() {
    ;(this.$refs.upload as any).submit()
  }
}
</script>

<style lang="scss" scoped>
.add-chart {
  .el-card {
    border-radius: 30px;
    margin: 35px;
  }
  .el-button--primary {
    background: #b4bdff;
  }
}
.hone {
  height: 545px;
  padding: 70px;
}
</style>
